#!d:\anaconda3\envs\office_automation\python.exe
# coding=utf-8
r"""
author: git config IVEN_CN && git config 13377529851@QQ.com
Date: 2024-08-13 17:22:36 +0800
LastEditTime: 2024-08-20 14:07:39 +0800
FilePath: \office_automation\FWNU\main.py
details: 查找未使用的款号, 通过easyocr识别图片中的文字, 然后使用everything接口搜索是否有对应的图片

Copyright (c) 2024 by IVEN, All Rights Reserved. 
"""
import os
import csv
import PIL.Image
import numpy as np
from openpyxl import load_workbook
import win32com.client as win32
import zipfile
import cv2
import easyocr
import shutil
from everytools import EveryTools

# import warnings
# warnings.filterwarnings("ignore", category=FutureWarning)

LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
SPECIAL = "!\"#$%&'()*+,./:;<=>?@[\\]^_`|}~"


class Convert:
    """xls文件转换器"""

    def __init__(self, path):
        self.path = path
        self.path_list = os.listdir(path)
        self.e = win32.gencache.EnsureDispatch("Excel.Application")
        self.e.DisplayAlerts = False  # 禁用警告
        self.e.EnableEvents = False  # 禁用宏

    def convert_file(self, i):
        """
        将xls文件转换为xlsx文件

        :param i: 文件名
        """
        if "xlsm" not in i and "xlsx" not in i:
            wb = self.e.Workbooks.Open(os.path.join(self.path, i))
            wb.SaveAs(os.path.join(self.path, i + "x"), FileFormat=51)
            wb.Close()
        elif "xlsx" not in i and "xlsm" in i:
            # 加载.xlsm文件
            wb = load_workbook(filename=os.path.join(self.path, i), read_only=False)
            # 保存为.xlsx文件
            filename = i[:-1] + "x"
            wb.save(os.path.join(self.path, filename))
        else:
            pass
        print(f"{i}转换完成")

    def xls2xlsx(self):
        """将xls文件批量转换为xlsx文件"""
        for i in self.path_list:
            self.convert_file(i)


reader = easyocr.Reader(["en"], gpu=True)


def detect(_img):
    img = cv2.cvtColor(_img, cv2.COLOR_BGR2GRAY)
    res = reader.readtext(img)
    for bbox, text, prob in res:  # bbox:文字框坐标, text:识别的文字, prob:识别的概率
        text = (
            text.replace(" ", "")
            .replace("I", "1")
            .replace("$", "S")
            .replace("1J", "U")
            .replace("[J", "U")
            .replace("}", "K")
            .replace("O", "0")
            .replace("o", "0")
            .replace("z", "2")
            .replace("?", "7")
        )
        if prob < 0.001:
            return None
        print(f"text:{text},probability:{prob}")
        return text


def deal_img(path: str):
    """
    处理图片
    ----
    从xlsx文件中将图片解压出来, 然后识别图片中的文字, 在使用everything接口搜索是否有对应的图片, 从而判断该款号是否使用过

    :param path: xlsx文件所在的文件夹路径
    """
    es = EveryTools()
    # region 解压图片
    path_list = os.listdir(path)
    path_list = [i for i in path_list if "xlsx" in i]
    images_path = os.path.join(path, "images")
    for index1, i in enumerate(path_list):
        with zipfile.ZipFile(os.path.join(path, i)) as f:  # 解压xlsx文件
            for file in f.namelist():
                if "xl/media" in file:
                    save_path = os.path.join(images_path, f"xl_{index1}")
                    f.extract(file, save_path)
    # endregion

    # region 读取图片
    img_path_list = get_all_files(images_path)
    unused_img_folder = os.path.join(path, "unused_img")
    unused_img_csv = os.path.join(path, "unused.csv")
    try:
        os.mkdir(unused_img_folder)
    except FileExistsError:
        pass
    for i in img_path_list:
        img0 = cv2.imread(i)
        img = img0[:150, :, :]
        text = detect(img)

        folder = os.path.dirname(i)
        folder = os.path.dirname(folder)
        folder = os.path.dirname(folder)
        folder = os.path.basename(folder)
        index_temp = int(folder.split("_")[-1])

        from_folder = path_list[index_temp]

        if text is not None:  # 识别到文字
            try:
                if text[-4] in LETTERS and text[-3:].isdigit():
                    pic_id = text[-4:]
                    es.search_pic(pic_id)
                    if es.get_num_total_file() == 0:
                        PIL.Image.fromarray(cv2.cvtColor(img0, cv2.COLOR_BGR2RGB)).save(
                            os.path.join(unused_img_folder, f"{pic_id}.jpg")
                        )
                        with open(unused_img_csv, "a", newline="", encoding="gbk") as f:
                            writer = csv.writer(f)
                            writer.writerow([pic_id, from_folder])

            except:
                pass
    shutil.rmtree(os.path.join(path, "images"))
    # endregion


def get_all_files(path: str):
    """获取文件夹下所有文件的路径"""
    path_list = []
    for root, dirs, files in os.walk(path):
        for file in files:
            path_list.append(os.path.join(root, file))
    return path_list


def readIMG(_path: str):
    """读取图片
    * _path: 图片路径"""
    img = PIL.Image.open(_path)
    img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
    return img


if __name__ == "__main__":
    PATH = r"D:\code_python\office_automation\test-23"
    # --------------xls转换为xlsx----------------
    # converter = Convert(PATH)
    # converter.xls2xlsx()

    # --------------批量解压图片并且识别----------------
    deal_img(PATH)

    # res = get_all_files('05-印花PNG')
    # print(res)
